{% extends "base.html" %}

{% block title %}{{ novel.title }} - 畅读小说网{% endblock %}

{% block content %}
<style>
    /* 整体容器样式 */
   .novel-detail-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    /* 面包屑导航样式 */
   .breadcrumb {
        font-size: 0.9rem;
        color: #666;
        margin-bottom: 20px;
    }

   .breadcrumb a {
        color: #007BFF;
        text-decoration: none;
    }

   .breadcrumb a:hover {
        text-decoration: underline;
    }

    /* 小说信息部分样式 */
   .novel-info-section {
        display: flex;
        gap: 20px;
        margin-bottom: 40px;
    }

   .novel-cover {
        width: 200px;
        height: 300px;
        position: relative;
        overflow: hidden;
    }

   .novel-cover img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

   .no-cover {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f0f0f0;
        color: #999;
    }

   .novel-info {
        flex: 1;
    }

   .novel-title {
        font-size: 2.5rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 10px;
    }

   .novel-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 20px;
    }

   .meta-item {
        display: flex;
        align-items: center;
    }

   .meta-item .label {
        font-weight: bold;
        margin-right: 5px;
    }

   .meta-item .value {
        color: #666;
    }

   .novel-actions {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
    }

   .btn-read,
   .btn-add-bookshelf,
   .btn-in-bookshelf,
   .btn-continue,
   .btn-reverse,
   .btn-load-more {
        padding: 10px 20px;
        border-radius: 5px;
        text-decoration: none;
        display: inline-block;
        background-color: #007BFF;
        color: white;
        border: none;
        cursor: pointer;
    }

   .btn-read:hover,
   .btn-add-bookshelf:hover,
   .btn-in-bookshelf:hover,
   .btn-continue:hover,
   .btn-reverse:hover,
   .btn-load-more:hover {
        background-color: #0056b3;
    }

   .novel-description h3 {
        font-size: 1.2rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 10px;
    }

   .description-content {
        color: #666;
        line-height: 1.6;
    }

    /* 章节列表部分样式 */
   .novel-chapters-section {
        margin-bottom: 40px;
    }

   .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

   .section-header h2 {
        font-size: 1.8rem;
        font-weight: bold;
        color: #333;
    }

   .chapter-controls {
        display: flex;
        gap: 10px;
    }

   .chapter-list {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

   .chapter-item {
        padding: 10px;
        background-color: #f9f9f9;
        border-radius: 5px;
    }

   .chapter-item a {
        color: #333;
        text-decoration: none;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

   .chapter-item a:hover {
        color: #007BFF;
    }

   .last-read {
        background-color: #fff3cd;
    }

   .last-read-mark {
        color: #ffc107;
        font-size: 0.9rem;
    }

   .no-chapters {
        color: #999;
        text-align: center;
        padding: 20px;
    }

   .chapter-pagination {
        text-align: center;
        margin-top: 20px;
    }

    /* 作者其他作品部分样式 */
   .novel-author-section h3 {
        font-size: 1.5rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 20px;
    }

   .author-novels {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
    }

   .author-novel-item {
        width: calc(33.333% - 20px);
        display: flex;
        gap: 10px;
    }

   .author-novel-item .novel-cover {
        width: 80px;
        height: 120px;
    }

   .author-novel-item .novel-info {
        flex: 1;
    }

   .author-novel-item .novel-title {
        font-size: 1.2rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 5px;
    }

   .author-novel-item .novel-category {
        color: #666;
    }

   .no-author-novels {
        color: #999;
        text-align: center;
        padding: 20px;
    }
</style>
<div class="novel-detail-container">
    <div class="novel-detail-header">
        <div class="breadcrumb">
            <a href="{% url 'frontend_home' %}">首页</a> &gt;
            <a href="{% url 'novel_list' %}?category={{ novel.category.id }}">{{ novel.category.name }}</a> &gt;
            <span>{{ novel.title }}</span>
        </div>
    </div>

    <div class="novel-detail-content">
        <div class="novel-info-section">
            <div class="novel-cover">
                {% if novel.cover %}
                    <img src="{{ novel.cover.url }}" alt="{{ novel.title }}">
                {% else %}
                    <div class="no-cover">暂无封面</div>
                {% endif %}
            </div>

            <div class="novel-info">
                <h1 class="novel-title">{{ novel.title }}</h1>

                <div class="novel-meta">
                    <div class="meta-item author">
                        <span class="label">作者：</span>
                        <span class="value">{{ novel.author.username }}</span>
                    </div>
                    <div class="meta-item category">
                        <span class="label">分类：</span>
                        <span class="value">{{ novel.category.name }}</span>
                    </div>
                    <div class="meta-item status">
                        <span class="label">状态：</span>
                        <span class="value">{{ novel.get_status_display }}</span>
                    </div>
                    <div class="meta-item chapters">
                        <span class="label">章节：</span>
                        <span class="value">{{ novel.chapters.count }}章</span>
                    </div>
                    <div class="meta-item bookshelf">
                        <span class="label">收藏：</span>
                        <span class="value">{{ novel.in_bookshelves.count }}</span>
                    </div>
                    <div class="meta-item update-time">
                        <span class="label">更新：</span>
                        <span class="value">{{ novel.updated_at|date:"Y-m-d H:i" }}</span>
                    </div>
                </div>

                <div class="novel-actions">
                    <a href="{% url 'read_novel' novel.id %}" class="btn-read">开始阅读</a>

                    {% if user.is_authenticated %}
                        {% if is_in_bookshelf %}
                            <a href="javascript:void(0);" id="btn-remove-bookshelf" class="btn-in-bookshelf">已加入书架</a>
                        {% else %}
                            <a href="javascript:void(0);" id="btn-add-bookshelf" class="btn-add-bookshelf">加入书架</a>
                        {% endif %}
                    {% endif %}

                    {% if last_read_chapter %}
                        <a href="{% url 'read_chapter' novel.id last_read_chapter.id %}" class="btn-continue">继续阅读</a>
                    {% endif %}
                </div>

                <div class="novel-description">
                    <h3>内容简介</h3>
                    <div class="description-content">
                        {{ novel.description|linebreaks }}
                    </div>
                </div>
            </div>
        </div>

        <div class="novel-chapters-section">
            <div class="section-header">
                <h2>章节列表</h2>
                <div class="chapter-controls">
                    <button id="btn-reverse" class="btn-reverse">倒序</button>
                </div>
            </div>

            <div class="chapter-list" id="chapter-list">
                {% if chapters %}
                    {% for chapter in chapters %}
                    <div class="chapter-item {% if last_read_chapter.id == chapter.id %}last-read{% endif %}">
                        <a href="{% url 'read_chapter' novel.id chapter.id %}">
                            {{ chapter.title }}
                            {% if last_read_chapter.id == chapter.id %}
                                <span class="last-read-mark">上次读到</span>
                            {% endif %}
                        </a>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="no-chapters">
                        <p>暂无章节</p>
                    </div>
                {% endif %}
            </div>

            {% if chapters.count > 30 %}
            <div class="chapter-pagination">
                <a href="javascript:void(0);" id="load-more" class="btn-load-more">加载更多章节</a>
            </div>
            {% endif %}
        </div>

        <div class="novel-author-section">
            <h3>作者其他作品</h3>

            {% if author_novels %}
            <div class="author-novels">
                {% for author_novel in author_novels %}
                    {% if author_novel.id != novel.id %}
                    <div class="author-novel-item">
                        <div class="novel-cover">
                            {% if author_novel.cover %}
                                <img src="{{ author_novel.cover.url }}" alt="{{ author_novel.title }}">
                            {% else %}
                                <div class="no-cover">暂无封面</div>
                            {% endif %}
                        </div>
                        <div class="novel-info">
                            <h4 class="novel-title">
                                <a href="{% url 'novel_detail' author_novel.id %}">{{ author_novel.title }}</a>
                            </h4>
                            <p class="novel-category">{{ author_novel.category.name }}</p>
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            </div>
            {% else %}
            <div class="no-author-novels">
                <p>作者暂无其他作品</p>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 加入/移出书架
        const addBookshelfBtn = document.getElementById('btn-add-bookshelf');
        const removeBookshelfBtn = document.getElementById('btn-remove-bookshelf');

        if (addBookshelfBtn) {
            addBookshelfBtn.addEventListener('click', function() {
                addToBookshelf();
            });
        }

        if (removeBookshelfBtn) {
            removeBookshelfBtn.addEventListener('click', function() {
                removeFromBookshelf();
            });
        }

        function addToBookshelf() {
            fetch('/api/bookshelf/add_to_bookshelf/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    novel_id: {{ novel.id }}
                })
            })
           .then(response => response.json())
           .then(data => {
                if (data.detail) {
                    // 刷新页面以显示更新后的状态
                    window.location.reload();
                }
            })
           .catch(error => {
                console.error('Error:', error);
            });
        }

        function removeFromBookshelf() {
            fetch('/api/bookshelf/remove_from_bookshelf/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    novel_id: {{ novel.id }}
                })
            })
           .then(response => response.json())
           .then(data => {
                if (data.detail) {
                    // 刷新页面以显示更新后的状态
                    window.location.reload();
                }
            })
           .catch(error => {
                console.error('Error:', error);
            });
        }

        // 获取CSRF Token
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // 章节列表倒序显示
        const reverseBtn = document.getElementById('btn-reverse');
        const chapterList = document.getElementById('chapter-list');

        reverseBtn.addEventListener('click', function() {
            const chapters = Array.from(chapterList.children);
            chapters.reverse();

            // 清空章节列表
            while (chapterList.firstChild) {
                chapterList.removeChild(chapterList.firstChild);
            }

            // 重新添加章节（倒序）
            chapters.forEach(chapter => {
                chapterList.appendChild(chapter);
            });

            // 更改按钮文本
            if (reverseBtn.textContent === '倒序') {
                reverseBtn.textContent = '正序';
            } else {
                reverseBtn.textContent = '倒序';
            }
        });

        // 加载更多章节
        const loadMoreBtn = document.getElementById('load-more');
        if (loadMoreBtn) {
            let currentPage = 1;

            loadMoreBtn.addEventListener('click', function() {
                currentPage++;

                fetch(`/api/novels/${novel.id}/chapters/?page=${currentPage}`)
               .then(response => response.json())
               .then(data => {
                    if (data.results && data.results.length > 0) {
                        // 添加新章节到列表
                        data.results.forEach(chapter => {
                            const chapterItem = document.createElement('div');
                            chapterItem.className = 'chapter-item';

                            if ({{ last_read_chapter.id|default:0 }} === chapter.id) {
                                chapterItem.classList.add('last-read');
                            }

                            chapterItem.innerHTML = `
                                <a href="/novels/${novel.id}/read/${chapter.id}/">
                                    ${chapter.title}
                                    ${{ last_read_chapter.id|default:0 }} === chapter.id ? '<span class="last-read-mark">上次读到</span>' : ''}
                                </a>
                            `;

                            chapterList.appendChild(chapterItem);
                        });

                        // 如果没有更多页面，隐藏按钮
                        if (!data.next) {
                            loadMoreBtn.style.display = 'none';
                        }
                    } else {
                        loadMoreBtn.style.display = 'none';
                    }
                })
               .catch(error => {
                    console.error('Error:', error);
                });
            });
        }
    });
</script>
{% endblock %}    